package com.hirsi.common.core.interceptor;

import cn.hutool.core.util.StrUtil;
import com.hirsi.common.core.constant.CommonConstant;
import com.hirsi.common.core.constant.RedisConstant;
import com.hirsi.common.core.handler.DeveloperCodeTenantLineHandler;
import com.hirsi.common.core.util.HttpContextUtil;
import com.hirsi.common.core.enums.ExceptionStatusEnum;
import com.hirsi.common.core.exception.ServerRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 访问拦截器
 * IP拦截，流量控制
 */
@Slf4j
@Component
public class HttpRequestHandlerInterceptor implements IHandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private DeveloperCodeTenantLineHandler developerCodeTenantLineHandler;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //判断是否在黑名单，未实现...
        
        String ipAddr = HttpContextUtil.getIpAddr();
        String key = String.format(RedisConstant.FLOW_CONTROL_PREFIX, ipAddr, HttpContextUtil.getUrl());
        //同一IP、同一接口访问间隔控制
        if (Boolean.TRUE.equals(redisTemplate.hasKey(key))) throw new ServerRuntimeException(ExceptionStatusEnum.FLOW_CONTROL);
        //单位时间内同一IP请求数量控制
        Long size = redisTemplate.opsForValue().size(String.format(RedisConstant.FLOW_CONTROL_IP_PREFIX, ipAddr));
        if (size != null && size >= RedisConstant.FLOW_CONTROL_EXPIRE_TIME * CommonConstant.FLOW_CONTROL_IP_MAX_SIZE) {
            throw new ServerRuntimeException(ExceptionStatusEnum.FLOW_CONTROL);
        }
        redisTemplate.opsForValue().set(key, StrUtil.EMPTY, RedisConstant.FLOW_CONTROL_EXPIRE_TIME, TimeUnit.SECONDS);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.warn("接口请求完成，清除租户线程变量");
        developerCodeTenantLineHandler.setTenantId(null);
    }

    @Override
    public String[] addPaths() {
        return new String[]{"/**"};
    }

    @Override
    public String[] excludePaths() {
        return new String[0];
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
